package com.haierCamera.customapplication.ui.zxing.activity;

import android.Manifest;
import android.app.Activity;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.google.zxing.BinaryBitmap;
import com.google.zxing.ChecksumException;
import com.google.zxing.DecodeHintType;
import com.google.zxing.FormatException;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.NotFoundException;
import com.google.zxing.PlanarYUVLuminanceSource;
import com.google.zxing.Result;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.QRCodeReader;
import com.haierCamera.customapplication.R;
import com.haierCamera.customapplication.api.ApiService;
import com.haierCamera.customapplication.ui.business.Business;
import com.haierCamera.customapplication.ui.main.CameraDeviceAddActivity;
import com.haierCamera.customapplication.ui.main.CameraSerialNextActivity;
import com.haierCamera.customapplication.ui.main.HZKLEditCameraNameActivity;
import com.haierCamera.customapplication.ui.zxing.camera.CameraManager;
import com.haierCamera.customapplication.ui.zxing.decode.DecodeThread;
import com.haierCamera.customapplication.ui.zxing.decode.RGBLuminanceSource;
import com.haierCamera.customapplication.ui.zxing.decode.Utils;
import com.haierCamera.customapplication.ui.zxing.utils.BeepManager;
import com.haierCamera.customapplication.ui.zxing.utils.CaptureActivityHandler;
import com.haierCamera.customapplication.ui.zxing.utils.InactivityTimer;
import com.haierCamera.customapplication.ui.zxing.view.ErrorDialog;
import com.haierCamera.customapplication.utils.FlashlightUtils;
import com.haierCamera.customapplication.utils.ResourceConvertUtils;
import com.haierCamera.customapplication.utils.android.HttpErrorProcess;
import com.lechange.opensdk.api.bean.CheckDeviceBindOrNot;
import com.lechange.opensdk.api.bean.DeviceOnline;
//import com.komlin.nulle.R;
//import com.komlin.nulle.zxing.camera.CameraManager;
//import com.komlin.nulle.zxing.decode.DecodeThread;
//import com.komlin.nulle.zxing.decode.RGBLuminanceSource;
//import com.komlin.nulle.zxing.decode.Utils;
//import com.komlin.nulle.zxing.utils.BeepManager;
//import com.komlin.nulle.zxing.utils.CaptureActivityHandler;
//import com.komlin.nulle.zxing.utils.InactivityTimer;
//import com.komlin.nulle.zxing.view.ErrorDialog;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.nio.charset.Charset;
import java.util.Hashtable;

import javax.inject.Inject;

import androidx.appcompat.app.AlertDialog;
import androidx.core.app.ActivityCompat;

import dagger.Lazy;
import dagger.android.DaggerActivity;
import dagger.android.support.DaggerAppCompatActivity;

public final class CaptureActivity extends DaggerAppCompatActivity implements SurfaceHolder.Callback {
    private static final String TAG = CaptureActivity.class.getSimpleName();
    private static final int REQUEST_CODE = 234;
    private String photo_path;
    private Bitmap scanBitmap;

    private CameraManager cameraManager;
    private CaptureActivityHandler handler;
    private InactivityTimer inactivityTimer;
    private BeepManager beepManager;

    private SurfaceView scanPreview = null;
    private RelativeLayout scanContainer;
    private RelativeLayout scanCropView;
    private ImageView scanLine;
    //    private RelativeLayout rl_back;
//    private TextView tv_bd;
    private ImageView img_return;
    private ImageView iv_serial_add;
    private ImageView iv_light;
    private LinearLayout layout_add_from_ph, layout_serial_add;

    private Rect mCropRect = null;
    private String type;
    @Inject
    ApiService apiService;
    @Inject
    Lazy<HttpErrorProcess> errorProcessLazy;

    public Handler getHandler() {
        return handler;
    }

    public CameraManager getCameraManager() {
        return cameraManager;
    }

    private boolean isHasSurface = false;
    private boolean isLightOn = false;

    private ProgressDialog mLoadingDialog;

    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(R.layout.hzkl_activity_capture);
        type = getIntent().getStringExtra("type");
        scanPreview = (SurfaceView) findViewById(R.id.capture_preview);
        scanContainer = (RelativeLayout) findViewById(R.id.capture_container);
        scanCropView = (RelativeLayout) findViewById(R.id.capture_crop_view);
        scanLine = (ImageView) findViewById(R.id.capture_scan_line);
//        rl_back = (RelativeLayout) findViewById(R.id.rl_back);
//        tv_bd = (TextView) findViewById(R.id.tv_bd);
        inactivityTimer = new InactivityTimer(this);
        beepManager = new BeepManager(this);
        img_return = (ImageView) findViewById(R.id.img_return);
        iv_serial_add = (ImageView) findViewById(R.id.iv_serial_add);
        iv_light = (ImageView) findViewById(R.id.iv_light);
        layout_add_from_ph = (LinearLayout) findViewById(R.id.layout_add_from_ph);
        layout_serial_add = (LinearLayout) findViewById(R.id.layout_serial_add);

        TranslateAnimation animation = new TranslateAnimation(Animation.RELATIVE_TO_PARENT
                , 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f
                , Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT,
                0.96f);
        animation.setDuration(4500);
        animation.setRepeatCount(-1);
        animation.setRepeatMode(Animation.RESTART);
        scanLine.startAnimation(animation);

        img_return.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        layout_serial_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(CaptureActivity.this
                        , CameraSerialNextActivity.class));
            }
        });
        layout_add_from_ph.setOnClickListener((v) -> {
            photo();
        });
        iv_light.setOnClickListener((v) -> {
            doFlashLight();
        });

        mLoadingDialog = new ProgressDialog(this);
        mLoadingDialog.setMessage("请稍后");
    }

    public void showLoadingDialog() {
        if (null == mLoadingDialog) {
            return;
        }
        mLoadingDialog.setCanceledOnTouchOutside(true);
        mLoadingDialog.show();
    }

    public void showLoadingDialog(String message) {
        if (null == mLoadingDialog) {
            return;
        }
        mLoadingDialog.setMessage(message);
        mLoadingDialog.show();
    }

    public void dismissLoadingDialog() {
        if (null == mLoadingDialog) {
            return;
        }
        mLoadingDialog.dismiss();
    }

    private void doFlashLight() {

        if (new FlashlightUtils().hasFlashlight(this)) {
            if (!isLightOn) {
                isLightOn = true;
                cameraManager.openLight();
            } else {
                isLightOn = false;
                cameraManager.offLight();
            }
        } else {
            Toast.makeText(this, "该设备不支持闪光灯", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        cameraManager = new CameraManager(getApplication());
        handler = null;
        if (isHasSurface) {
            initCamera(scanPreview.getHolder());
        } else {
            scanPreview.getHolder().addCallback(this);
        }
        inactivityTimer.onResume();
    }

    @Override
    protected void onPause() {
        Log.i("TAG", "onPause");
        if (handler != null) {
            handler.quitSynchronously();
            handler = null;
        }
        inactivityTimer.onPause();
        beepManager.close();
        cameraManager.closeDriver();
        if (!isHasSurface) {
            scanPreview.getHolder().removeCallback(this);
        }
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        inactivityTimer.shutdown();
        super.onDestroy();
    }

    private void photo() {
        Intent innerIntent = new Intent(); // "android.intent.action.GET_CONTENT"
        if (Build.VERSION.SDK_INT < 19) {
            innerIntent.setAction(Intent.ACTION_GET_CONTENT);
        } else {
            innerIntent.setAction(Intent.ACTION_OPEN_DOCUMENT);
        }
        innerIntent.setType("image/*");
        Intent wrapperIntent = Intent.createChooser(innerIntent, "选择二维码图片");
        CaptureActivity.this.startActivityForResult(wrapperIntent, REQUEST_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUEST_CODE:
                    String[] proj = {MediaStore.Images.Media.DATA};
                    // 获取选中图片的路径
                    Cursor cursor = getContentResolver().query(data.getData(), proj, null, null, null);
                    if (cursor.moveToFirst()) {
                        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                        photo_path = cursor.getString(column_index);
                        if (photo_path == null) {
                            photo_path = Utils.getPath(getApplicationContext(), data.getData());
//                            Log.i("123path  Utils", photo_path);
                        }
                        Log.i("123path", photo_path);
                    }
                    cursor.close();
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            Result result = scanningImage(photo_path);
                            // String result = decode(photo_path);
                            if (result == null) {
                                //Log.i("123", "   -----------");
                                Looper.prepare();
                                //Toast.makeText(getApplicationContext(), "图片格式有误", Toast.LENGTH_SHORT).show();
                                failed("未发现二维码");
                                Looper.loop();
                            } else {
                                //Log.i("123result", result.toString());
                                // Log.i("123result", result.getText());
                                // 数据返回
                                Log.i("TAG", "data_return_1-" + result.toString());

                                runOnUiThread(() -> {
                                    handleDecode(result, new Bundle());
                                });

//                                String recode = recode(result.toString());
//                                Intent data = new Intent();
//                                data.putExtra("result", recode);
//                                setResult(RESULT_OK, data);
//                                finish();
                            }
                        }
                    }).start();
                    break;
            }
        }
    }

    private ErrorDialog.Builder errbuilder;

    private void failed(String err) {
        errbuilder = new ErrorDialog.Builder(CaptureActivity.this);
        errbuilder.setTitle(err);
        errbuilder.setPositiveButton("我知道了", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        errbuilder.create().show();
    }

    // TODO: 解析部分图片
    protected Result scanningImage(String path) {
        if (TextUtils.isEmpty(path)) {
            return null;
        }
        // DecodeHintType 和EncodeHintType
        Hashtable<DecodeHintType, String> hints = new Hashtable<DecodeHintType, String>();
        hints.put(DecodeHintType.CHARACTER_SET, "utf-8"); // 设置二维码内容的编码
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true; // 先获取原大小
        scanBitmap = BitmapFactory.decodeFile(path, options);
        options.inJustDecodeBounds = false; // 获取新的大小

        int sampleSize = (int) (options.outHeight / (float) 200);

        if (sampleSize <= 0)
            sampleSize = 1;
        options.inSampleSize = sampleSize;
        scanBitmap = BitmapFactory.decodeFile(path, options);

        // --------------测试的解析方法---PlanarYUVLuminanceSource-这几行代码对project没作功----------

        LuminanceSource source1 = new PlanarYUVLuminanceSource(rgb2YUV(scanBitmap), scanBitmap.getWidth(),
                scanBitmap.getHeight(), 0, 0, scanBitmap.getWidth(),
                scanBitmap.getHeight(), false);
        BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(source1));
        MultiFormatReader reader1 = new MultiFormatReader();
        Result result1;
        try {
            result1 = reader1.decode(binaryBitmap);
            String content = result1.getText();
            //Log.i("123content", content);
        } catch (NotFoundException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        // ----------------------------

        RGBLuminanceSource source = new RGBLuminanceSource(scanBitmap);
        BinaryBitmap bitmap1 = new BinaryBitmap(new HybridBinarizer(source));
        QRCodeReader reader = new QRCodeReader();
        try {

            return reader.decode(bitmap1, hints);

        } catch (NotFoundException e) {

            e.printStackTrace();

        } catch (ChecksumException e) {

            e.printStackTrace();

        } catch (FormatException e) {

            e.printStackTrace();

        }

        return null;

    }

    /**
     * 中文乱码
     * <p>
     * 暂时解决大部分的中文乱码 但是还有部分的乱码无法解决 .
     * <p>
     * 如果您有好的解决方式 请联系 2221673069@qq.com
     * <p>
     * 我会很乐意向您请教 谢谢您
     *
     * @return
     */
    private String recode(String str) {
        String formart = "";

        try {
            boolean ISO = Charset.forName("ISO-8859-1").newEncoder()
                    .canEncode(str);
            if (ISO) {
                formart = new String(str.getBytes("ISO-8859-1"), "GB2312");
                //Log.i("1234      ISO8859-1", formart);
            } else {
                formart = str;
                //Log.i("1234      stringExtra", str);
            }
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return formart;
    }

    /**
     * //TODO: TAOTAO 将bitmap由RGB转换为YUV //TOOD: 研究中
     *
     * @param bitmap 转换的图形
     * @return YUV数据
     */
    public byte[] rgb2YUV(Bitmap bitmap) {
        // 该方法来自QQ空间
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        int[] pixels = new int[width * height];
        bitmap.getPixels(pixels, 0, width, 0, 0, width, height);

        int len = width * height;
        byte[] yuv = new byte[len * 3 / 2];
        int y, u, v;
        for (int i = 0; i < height; i++) {
            for (int j = 0; j < width; j++) {
                int rgb = pixels[i * width + j] & 0x00FFFFFF;

                int r = rgb & 0xFF;
                int g = (rgb >> 8) & 0xFF;
                int b = (rgb >> 16) & 0xFF;

                y = ((66 * r + 129 * g + 25 * b + 128) >> 8) + 16;
                u = ((-38 * r - 74 * g + 112 * b + 128) >> 8) + 128;
                v = ((112 * r - 94 * g - 18 * b + 128) >> 8) + 128;

                y = y < 16 ? 16 : (y > 255 ? 255 : y);
                u = u < 0 ? 0 : (u > 255 ? 255 : u);
                v = v < 0 ? 0 : (v > 255 ? 255 : v);

                yuv[i * width + j] = (byte) y;
                // yuv[len + (i >> 1) * width + (j & ~1) + 0] = (byte) u;
                // yuv[len + (i >> 1) * width + (j & ~1) + 1] = (byte) v;
            }
        }
        return yuv;
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        if (holder == null) {
            //Log.e(TAG, "*** WARNING *** surfaceCreated() gave us a null surface!");
        }
        if (!isHasSurface) {
            isHasSurface = true;
            initCamera(holder);
        }
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        isHasSurface = false;
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

    }

    /**
     * A valid barcode has been found, so give an indication of success and show
     * the results.
     *
     * @param rawResult The contents of the barcode.
     * @param bundle    The extras
     */

    // 7P7S设备：{SN:6A0376DPAJ13266,DT:TP7S,SC:L2B6E508,NC:018}
    public void handleDecode(Result rawResult, Bundle bundle) {
        inactivityTimer.onActivity();
        beepManager.playBeepSoundAndVibrate();
//        Intent resultIntent = new Intent();
        if (null != type && type.equals("1")) {
            Log.i("TAG", "data_return_2-" + rawResult.toString());
//            bundle.putString("result", rawResult.toString());
//            resultIntent.putExtras(bundle);
//            this.setResult(RESULT_OK, resultIntent);
            String sn = "";
            String sc = "";
            String dt = "";
            if (rawResult.toString().contains("{")) {
                JSONObject json = parseJson(rawResult.toString());
                try {
                    sn = json.getString("SN");
                } catch (Exception e) {
                    e.printStackTrace();
                }


                if (rawResult.toString() != null && rawResult.toString().contains("SC:")) {

                    try {
                        sc = json.getString("SC");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else if (rawResult.toString() != null && rawResult.toString().contains("RC:")) {
                    try {
                        sc = json.getString("RC");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                if (rawResult.toString() != null && rawResult.toString().contains("DT:")) {

                    try {
                        dt = json.getString("DT");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            } else {
                sn = rawResult.toString();
            }

            showLoadingDialog();
            checkOnBindAndRemind(sn, sc, dt);
        }
    }

    private JSONObject parseJson(String string) {
        // { 后面
        // } 前面
        // : 前面和后面
        // , 前面和后面
        string = string.replaceAll("\\{", "{\"");
        string = string.replaceAll("\\}", "\"}");
        string = string.replaceAll(":", "\":\"");
        string = string.replaceAll(",", "\",\"");
        JSONObject json = null;
        try {
            json = new JSONObject(string);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return json;

    }

    void restartCamera() {
        Log.d(TAG, "hasSurface " + isHasSurface);

        initCamera(scanPreview.getHolder());
        // 恢复活动监控器
        inactivityTimer.onResume();
    }

    void closeCamera() {
        if (handler != null) {
            handler.quitSynchronously();
            handler = null;
        }
        inactivityTimer.onPause();

        // 关闭摄像头
        cameraManager.closeDriver();
    }


    public void checkOnBindAndRemind(String sn, String sc, String dt) {
        Business.getInstance().checkBindOrNot(sn,
                new Handler() {
                    @Override
                    public void handleMessage(Message msg) {
                        // TODO Auto-generated method stub
                        super.handleMessage(msg);
                        Business.RetObject retObject = (Business.RetObject) msg.obj;
                        if (msg.what == 0) {
                            CheckDeviceBindOrNot.Response resp = (CheckDeviceBindOrNot.Response) retObject.resp;
                            if (!resp.data.isBind) {
                                showWifiConfig(sn, sc, dt);

                            } else if (resp.data.isBind && resp.data.isMine) {
                                dismissLoadingDialog();

                                showWifiConfig(sn, sc, dt);
//                                Toast.makeText(CaptureActivity.this, "" + getString(R.string.HZKLtoast_adddevice_already_binded_by_self)
//                                        , Toast.LENGTH_SHORT).show();
//                                finish();
                            } else {
                                dismissLoadingDialog();
//                                toast(getString(R.string.HZKLtoast_adddevice_already_binded_by_others));
//                                Toast.makeText(CaptureActivity.this, "" + getString(R.string.HZKLtoast_adddevice_already_binded_by_others)
//                                        , Toast.LENGTH_SHORT).show();
                                AlertDialog dialog = new AlertDialog.Builder(CaptureActivity.this)
                                        .setMessage("" + getString(R.string.HZKLtoast_adddevice_already_binded_by_others))
                                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                dialog.dismiss();
                                            }
                                        })
                                        .create();

                                dialog.show();
//                                finish();
                            }
                        } else {
                            dismissLoadingDialog();
                            Log.i("TAG", "checkOnBindAndRemind-" + retObject.mMsg);
//                            toast(retObject.mMsg);
//                            Toast.makeText(CaptureActivity.this, "" + retObject.mMsg
//                                    , Toast.LENGTH_SHORT).show();
                            AlertDialog dialog = new AlertDialog.Builder(CaptureActivity.this)
                                    .setMessage("" + retObject.mMsg)
                                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            dialog.dismiss();
                                        }
                                    })
                                    .create();
                            dialog.show();
//                            finish();
                        }
//                        finish();
                    }
                });
    }

    /**
     * 开启无线配网流程（权限检查，配对说明）
     */
    public void showWifiConfig(String sn, String sc, String dt) {
        boolean isMinSDKM = Build.VERSION.SDK_INT < 23;
        boolean isGranted = ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED;
        if (isMinSDKM || isGranted) {

            Log.i("TAG", "checkOnline");
            checkOnline(sn, sc, dt);
            // 开启无线配对
            return;
        }

        Log.i("TAG", "requestLocationPermission");
        requestLocationPermission();
    }

    /**
     * 请求相关权限
     */
    private void requestLocationPermission() {
        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.ACCESS_FINE_LOCATION)) {

            Log.d("Uriah", "Uriah + shouldShowRequestPermission true");
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                    1);
        } else {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                    1);
        }
    }

    /**
     * 校验在线
     */
    private void checkOnline(String sn, String sc, String dt) {
        Business.getInstance().checkOnline(sn,
                new Handler() {
                    @Override
                    public void handleMessage(Message msg) {
                        Business.RetObject retObject = (Business.RetObject) msg.obj;
                        Log.i("TAG", "CaptureActivity-msg.what-" + msg.what);
                        switch (msg.what) {
                            case 0:
                                if (((DeviceOnline.Response) retObject.resp).data.onLine.equals("1")) {
                                    Log.i("TAG", "onLine");

                                    if (sc != null
                                            && sc.length() == 8) {

                                        addByService(sn, sc);
                                    } else {

                                        unBindDeviceInfo(sn, sc);
                                    }
                                } else {
                                    dismissLoadingDialog();
//                                    showEnsureDescription(sn,sc,dt);
                                    Intent resultIntent = new Intent();
                                    Bundle bundle = new Bundle();
                                    bundle.putString("sn", sn);
                                    bundle.putString("sc", sc);
                                    bundle.putString("dt", dt);
                                    resultIntent.putExtras(bundle);
                                    CaptureActivity.this.setResult(RESULT_OK, resultIntent);
                                    finish();

                                }
                                break;
                            case -1000:
                                Log.e(TAG, "check_online_respond : -1000");
                                dismissLoadingDialog();
//                                mHandler.obtainMessage(ON_LINE_FAILED).sendToTarget();
                                break;
                            default:
                                Log.e(TAG, "checkonline  :  " + msg.what);
                                dismissLoadingDialog();
//                                mHandler.obtainMessage(ON_LINE_FAILED).sendToTarget();
                                break;
                        }
                    }
                });

    }

    /**
     * 显示状态说明
     */
    private void showEnsureDescription(String sn, String sc, String dt) {
        DialogInterface.OnClickListener dialogOnclicListener = new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                switch (which) {
                    case Dialog.BUTTON_POSITIVE:
                        Intent resultIntent = new Intent();
                        Bundle bundle = new Bundle();
                        bundle.putString("sn", sn);
                        bundle.putString("sc", sc);
                        bundle.putString("dt", dt);
                        resultIntent.putExtras(bundle);
                        CaptureActivity.this.setResult(RESULT_OK, resultIntent);
                        finish();
                        break;
                    case Dialog.BUTTON_NEGATIVE:
                        handler.restartPreviewAndDecode();
                        break;
                    case Dialog.BUTTON_NEUTRAL:
                        break;
                }
            }
        };
        // dialog参数设置
        android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(this); // 先得到构造器
        builder.setTitle(R.string.HZKLdevices_config_dialog_title); // 设置标题
        builder.setMessage(R.string.HZKLdevices_config_dialog_ensure); // 设置内容
        builder.setPositiveButton(R.string.HZKLdialog_positive,
                dialogOnclicListener);
        builder.setNegativeButton(R.string.HZKLdialog_nagative,
                dialogOnclicListener);
        builder.create().show();
    }

    private void unBindDeviceInfo(String sn, String sc) {
        if (!Business.getInstance().isOversea) {
            Business.getInstance().unBindDeviceInfo(sn, new Handler() {
                public void handleMessage(Message msg) {
                    String message = (String) msg.obj;
                    Log.d("TAG", "unBindDeviceInfo," + message);

                    if (msg.what == 0) {
                        if (message.contains("Auth")) {
//                            bindDevice();

                            Log.i("TAG", "addByService_1");
//                            if (key.equals( binding.edSecurity.getText().toString())) {
                            final EditText et = new EditText(CaptureActivity.this);
                            final AlertDialog dialog = new AlertDialog.Builder(CaptureActivity.this)
                                    .setTitle("请输入设备密码")
                                    .setView(et)
                                    .setPositiveButton(R.string.HZKLdialog_positive, null)
                                    .setNegativeButton(R.string.HZKLdialog_nagative, null)
                                    .create();
                            dialog.setCanceledOnTouchOutside(false);
                            if (!CaptureActivity.this.isFinishing() && !dialog.isShowing()) {
                                dialog.show();
                            }
                            dialog
                                    .getButton(AlertDialog.BUTTON_POSITIVE)
                                    .setOnClickListener((v) -> {
                                        if (TextUtils.isEmpty(et.getText())) {
                                            Toast.makeText(CaptureActivity.this, "输入不能为空", Toast.LENGTH_SHORT).show();
                                            return;
                                        }
                                        String key = et.getText().toString();
//                                    bindDevice();

                                        addByService(sn, key);
                                        dialog.dismiss();
                                    });
                            dialog.getButton(AlertDialog.BUTTON_NEGATIVE)
                                    .setOnClickListener((v) -> {
//                                            restartCamera();
                                        handler.restartPreviewAndDecode();
                                        dialog.dismiss();
                                    });

//                            }else {
//                                addByService(binding.edSn.getText().toString(), key);
//                            }

                        } else if (message.contains("RegCode")) {

                            addByService(sn, sc);
                        } else {
                            Log.i("TAG", "addByService_2");
                            String key = "";
                            addByService(sn, key);
//                            bindDevice();
                        }
                    } else {
                        Toast.makeText(CaptureActivity.this, "unBindDeviceInfo failed", Toast.LENGTH_SHORT).show();
                        Log.d(TAG, message);
                    }
                }
            });
        } else { //oversea
//            bindDevice();
            Log.i("TAG", "addByService_3");
            addByService(sn, sc);
        }

    }

    private void addByService(String serialNumber, String securityCode) {
        ResourceConvertUtils.convertToResource(apiService.addAndBind(serialNumber, securityCode))
                .observe(this, resource -> {
                    assert resource != null;
                    switch (resource.status) {
                        case ERROR:
                            dismissLoadingDialog();
                            Log.i("TAG", "ERROR--" + resource.errorCode + "/" + resource.toString());
                            errorProcessLazy.get().process(resource);
                            //finish();
                            showSnDialog(serialNumber);
                            break;
                        case SUCCESS:
                            dismissLoadingDialog();
                            Log.i("TAG", "addCameraByServiceSuccess--");
                            Toast.makeText(this, "添加成功", Toast.LENGTH_SHORT).show();

                            finish();

                            break;
                        case LOADING:
                            break;

                    }
                });
    }

    private void showSnDialog(String serialNumber) {
        final EditText et = new EditText(CaptureActivity.this);
        final AlertDialog dialog = new AlertDialog.Builder(CaptureActivity.this)
                .setTitle("请重新输入设备初始化密码")
                .setView(et)
                .setPositiveButton(R.string.HZKLdialog_positive, null)
                .setNegativeButton(R.string.HZKLdialog_nagative, null)
                .create();
        dialog.setCanceledOnTouchOutside(false);
        if (!CaptureActivity.this.isFinishing() && !dialog.isShowing()) {
            dialog.show();
        }
        dialog
                .getButton(AlertDialog.BUTTON_POSITIVE)
                .setOnClickListener((v) -> {
                    if (TextUtils.isEmpty(et.getText())) {
                        Toast.makeText(CaptureActivity.this, "输入不能为空", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    String key = et.getText().toString();
//                                    bindDevice();
                    addByService(serialNumber, key);
                    dialog.dismiss();
                });
        dialog.getButton(AlertDialog.BUTTON_NEGATIVE)
                .setOnClickListener((v) -> {
                    dialog.dismiss();
                });

    }

    private void initCamera(SurfaceHolder surfaceHolder) {
        if (surfaceHolder == null) {
            throw new IllegalStateException("No SurfaceHolder provided");
        }
        if (cameraManager.isOpen()) {
            Log.i("TAG", "cameraManager.isOpen()");
            //Log.w(TAG, "initCamera() while already open -- late SurfaceView callback?");
            return;
        }
        try {
            cameraManager.openDriver(surfaceHolder);
            // Creating the handler starts the preview, which can also throw a
            // RuntimeException.
            if (handler == null) {
                handler = new CaptureActivityHandler(this, cameraManager, DecodeThread.ALL_MODE);
            }
            initCrop();
        } catch (IOException ioe) {
            //Log.w(TAG, ioe);
            displayFrameworkBugMessageAndExit();
        } catch (RuntimeException e) {
            //Log.w(TAG, "Unexpected error initializing camera", e);
            displayFrameworkBugMessageAndExit();
        }
    }

    private void displayFrameworkBugMessageAndExit() {
        // camera error
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
//        builder.setTitle(getString(R.string.HZKLapp_name));
        builder.setTitle("");
        builder.setMessage("请开启摄像头权限");
        builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {

                finish();
            }
        });
        builder.setOnCancelListener(new DialogInterface.OnCancelListener() {

            @Override
            public void onCancel(DialogInterface dialog) {
                finish();
            }
        });
        builder.show();
    }

    public Rect getCropRect() {
        return mCropRect;
    }

    /**
     * 初始化截取的矩形区域
     */
    private void initCrop() {
        int cameraWidth = cameraManager.getCameraResolution().y;
        int cameraHeight = cameraManager.getCameraResolution().x;

        /** 获取布局中扫描框的位置信息 */
        int[] location = new int[2];
        scanCropView.getLocationInWindow(location);

        int cropLeft = location[0];
        int cropTop = location[1] - getStatusBarHeight();

        int cropWidth = scanCropView.getWidth();
        int cropHeight = scanCropView.getHeight();

        /** 获取布局容器的宽高 */
        int containerWidth = scanContainer.getWidth();
        int containerHeight = scanContainer.getHeight();

        /** 计算最终截取的矩形的左上角顶点x坐标 */
        int x = cropLeft * cameraWidth / containerWidth;
        /** 计算最终截取的矩形的左上角顶点y坐标 */
        int y = cropTop * cameraHeight / containerHeight;

        /** 计算最终截取的矩形的宽度 */
        int width = cropWidth * cameraWidth / containerWidth;
        /** 计算最终截取的矩形的高度 */
        int height = cropHeight * cameraHeight / containerHeight;

        /** 生成最终的截取的矩形 */
        mCropRect = new Rect(x, y, width + x, height + y);
    }

    private int getStatusBarHeight() {
        try {
            Class<?> c = Class.forName("com.android.internal.R$dimen");
            Object obj = c.newInstance();
            Field field = c.getField("status_bar_height");
            int x = Integer.parseInt(field.get(obj).toString());
            return getResources().getDimensionPixelSize(x);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

}